package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    @Transactional//事务注解————此方法涉及两个表的操作，需要原子性
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入一条数据
        dishMapper.insert(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            //向口味表插入多条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        //这里使用了PageHelper分页插件，会拦截dishMapper.find方法自动进行分页的配置
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<Dish> dishes = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(dishes.getTotal(), dishes.getResult());
    }


    //TODO 视频上的策略是如果有条件不满足，就所有的都不会进行删除
    // (但是我感觉可以优化一下，把满足条件的删除，
    // 不满足条件的返回给前端，让前端提示给用户，后端也可以抛出异常处理)

    //TODO 小瑕疵：如果传入的菜品有关联的套餐还有在起售的，返回给前端的提示信息是：菜品正在起售中，不能删除（应该是两个都要返还给前端更好一点）
    @Override
    public void delete(List<Long> ids) {
        //判断是否可以删除     视频上使用的是循环并一次次查询的方式，这里我使用的是批量查询的方式
        //1、查询当前菜品是否在售
        List<Integer> statusList = dishMapper.findStatusByIds(ids);
        if (statusList != null && statusList.size() > 0) {
            //TODO 这里是我按照视频上的逻辑写的代码
            int statusAll = statusList.get(0);
            if(statusAll == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            for(int i = 1;i < statusList.size();i++){
                if(statusAll != statusList.get(i)){
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
            }
        } else {
            //正常情况下不会出现这种情况   这里不进行else也行，让后面的逻辑执行，进行删除（因为不存在的菜品，也没得删）
            log.info("传入的菜品都不存在或者传入的菜品数量为空");
        }
        //2、查询当前菜品是否有关联的套餐
        List<Long> setmealIds = setmealDishMapper.findSetmealIdsByIds(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //删除数据
        //1、删除菜品表中的数据
        dishMapper.deleteByIds(ids);
        //2、删除菜品口味表数据 批量删除   视频上的是代码层面的循环删除
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishDTO getById(Long id) {
        Dish dish = dishMapper.getById(id);
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish, dishDTO);
        return dishDTO;
    }


    @Override
    public void update(DishDTO dishDTO) {
        //修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //修改菜品对应的口味信息
        //1. 删除当前菜品对应的口味数据
        //2.重新插入当前菜品对应的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
            }
        }

        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        dishFlavorMapper.insertBatch(flavors);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        dishMapper.updateStatus(status, id);
    }
}
